﻿using CPPEI.Coolzon.Common;
using CPPEI.Coolzon.UI;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;

namespace CPPEI.Coolzon.Designer.Views
{
    /// <summary>
    /// Interaction logic for DataSourceDetailWindow.xaml
    /// </summary>
    public partial class DataSourceDetailWindow : Window
    {
        private List<ServiceProxy.DesignServiceRef.DataSet> _tmpDataSetList;
        public ServiceProxy.DesignServiceRef.DataSource RetDataSource { get; private set; }
        private bool _IsNew = false;
        private ObservableCollection<ServiceProxy.DesignServiceRef.DataSet> _dataSetList;
        private string _tmpResult = string.Empty;
        public DataSourceDetailWindow(ServiceProxy.DesignServiceRef.DataSource dataSource = null)
        {
            InitializeComponent();
            if (dataSource != null)
            {
                _ctltbPwd.Password = dataSource.AuthenticationPassword;
                Title = "修改数据源";
            }
            else
            {
                Title = "新建数据源";
                _IsNew = true;
                dataSource = new ServiceProxy.DesignServiceRef.DataSource();
                dataSource.Id = Guid.NewGuid();
                dataSource.Name = "新建数据源";
                dataSource.Caption = "新建数据源";
                dataSource.Type = "DataBase";
                dataSource.Version = new Version("1.0");
                dataSource.RTVersion = new Version("1.0");
            }
            RetDataSource = dataSource;
            _ctlGrid.DataContext = RetDataSource;
        }

        private void _ctlAdd_Click(object sender, RoutedEventArgs e)
        {
            DataSetWindow window = new DataSetWindow(RetDataSource.Id);
            if (window.ShowDialog() == true)
            {
                _dataSetList.Add(window.RetDataSet);
            }
        }

        private void _ctlRemove_Click(object sender, RoutedEventArgs e)
        {
            _tmpResult = string.Empty;
            if (_ctlDataSetList.SelectedItems != null && _ctlDataSetList.SelectedItems.Count > 0)
            {
                if (MessageBox.Show("是否确定删除?", "提示", MessageBoxButton.YesNo) == MessageBoxResult.Yes)
                {
                    if (_tmpDataSetList == null)
                    {
                        _tmpDataSetList = new List<ServiceProxy.DesignServiceRef.DataSet>();
                    }
                    else
                    {
                        _tmpDataSetList.Clear();
                    }
                    foreach (var item in _ctlDataSetList.SelectedItems)
                    {
                        _tmpDataSetList.Add(item as ServiceProxy.DesignServiceRef.DataSet);
                    }
                    DeleteDataSet(_tmpDataSetList[0]);
                    ProgressbarWindow.Instance.ShowProgress(true);
                }
            }
            else
            {
                MessageBox.Show("请选择数据集");
            }
        }
        private void DeleteDataSet(ServiceProxy.DesignServiceRef.DataSet dataSet)
        {
            Event.NCL.NCLEventBus.Publish(new Event.NCL.BeginDeleteDataSetEvent(UIContext.Current.Token, RetDataSource.Id, dataSet.Id));
            _tmpDataSetList.Remove(dataSet);
        }
        [Subscribe]
        public void EndDeleteDataSet(Event.NCL.EndDeleteDataSetEvent @event)
        {
            ServiceProxy.DesignServiceRef.DataSet tmpDataSet = _dataSetList.First(a => a.Id == @event.DataSetId);
            if (@event.State == Event.NCL.NCLEventState.Failure)
            {
                _tmpResult += string.Format("{0}:{1}{2}", tmpDataSet.Name, "删除失败", Environment.NewLine);
                Logger.ErrorToTag(Library.LogTAG, "删除数据源 {0} 失败,{1}", tmpDataSet.Name, @event.Error);
            }
            else if (@event.State == Event.NCL.NCLEventState.Finished)
            {
                Dispatcher.Invoke(() =>
                {
                    _dataSetList.Remove(tmpDataSet);
                });
                _tmpResult += string.Format("{0}:{1}{2}", tmpDataSet.Name, "删除成功", Environment.NewLine);
                Logger.InfoToTag(Library.LogTAG, "删除数据源 {0} 成功", tmpDataSet.Name);
            }
            if (_tmpDataSetList.Count > 0)
            {
                DeleteDataSet(_tmpDataSetList[0]);
            }
            else
            {
                ProgressbarWindow.Instance.Complete();
                Dispatcher.Invoke(() =>
                {
                    CustomMessageBox.ShowInfo(_tmpResult, "删除结果");
                });
            }
        }

        private void _ctlEdit_Click(object sender, RoutedEventArgs e)
        {
            EditDataSet();
        }

        private void EditDataSet()
        {
            if (_ctlDataSetList.SelectedItem != null)
            {
                DataSetWindow window = new DataSetWindow(RetDataSource.Id, _ctlDataSetList.SelectedItem as ServiceProxy.DesignServiceRef.DataSet);
                window.ShowDialog();
            }
        }

        private void Button_Click(object sender, RoutedEventArgs e)
        {
            if (string.IsNullOrWhiteSpace(_ctltbName.Text))
            {
                Coolzon.UI.CustomMessageBox.ShowWarning("请输入名称");
                return;
            }
            RetDataSource.Id = (_ctlGrid.DataContext as ServiceProxy.DesignServiceRef.DataSource).Id;
            RetDataSource.Name = _ctltbName.Text;
            RetDataSource.Caption = _ctltbCaption.Text;
            RetDataSource.Type = _ctltbType.Text;
            Version tmpVersion;
            if (Version.TryParse(_ctltbVersion.Text, out tmpVersion))
            {
                RetDataSource.Version = tmpVersion;
            }
            if (Version.TryParse(_ctltbRuntimeVertion.Text, out tmpVersion))
            {
                RetDataSource.RTVersion = tmpVersion;
            }
            //if (_ctlcbCacheMode.SelectedItem != null)
            //{
            //RetDataSource.CacheMode = (Metadata.CacheMode)_ctlcbCacheMode.SelectedItem;
            //}
            RetDataSource.Address = _ctltbAddress.Text;
            RetDataSource.AuthenticationMode = _ctltbMode.Text;
            RetDataSource.AuthenticationUser = _ctltbUser.Text;
            RetDataSource.AuthenticationPassword = _ctltbPwd.Password;

            if (_IsNew)
            {
                Event.NCL.NCLEventBus.Publish(new Event.NCL.BeginCreateDataSourceEvent(UIContext.Current.Token, RetDataSource));
            }
            else
            {
                Event.NCL.NCLEventBus.Publish(new Event.NCL.BeginUpdateDataSourceEvent(UIContext.Current.Token, RetDataSource));
            }
            ProgressbarWindow.Instance.ShowProgress(true);
        }

        [Subscribe]
        public void EndCreateDataSourceEvent(Event.NCL.EndCreateDataSourceEvent @event)
        {
            ProgressbarWindow.Instance.Complete();
            if (@event.State == Event.NCL.NCLEventState.Failure)
            {
                Dispatcher.Invoke(() =>
                {
                    Coolzon.UI.CustomMessageBox.ShowError(string.Format("创建数据源失败"));
                    Logger.ErrorToTag(Library.LogTAG, string.Format("创建数据源失败,{0}", @event.Error));
                });
            }
            else if (@event.State == Event.NCL.NCLEventState.Finished)
            {
                Dispatcher.Invoke(() =>
                {
                    Coolzon.UI.CustomMessageBox.ShowInfo("创建成功");
                    DialogResult = true;
                });
            }
        }

        [Subscribe]
        public void EndUpdateDataSourceEvent(Event.NCL.EndUpdateDataSourceEvent @event)
        {
            ProgressbarWindow.Instance.Complete();
            if (@event.State == Event.NCL.NCLEventState.Failure)
            {
                Dispatcher.Invoke(() =>
                {
                    Coolzon.UI.CustomMessageBox.ShowError(string.Format("更新数据源失败"));
                    Logger.ErrorToTag(Library.LogTAG, string.Format("更新数据源失败,{0}", @event.Error));
                });
            }
            else if (@event.State == Event.NCL.NCLEventState.Finished)
            {
                Dispatcher.Invoke(() =>
                {
                    Coolzon.UI.CustomMessageBox.ShowInfo("更新成功");
                    DialogResult = true;
                });
            }
        }

        private void cancel_Click(object sender, RoutedEventArgs e)
        {
            DialogResult = false;
        }

        private void _ctlDataSetList_MouseDoubleClick(object sender, MouseButtonEventArgs e)
        {
            EditDataSet();
        }

        private void Window_Loaded(object sender, RoutedEventArgs e)
        {
            Event.NCL.NCLEventBus.Register(this);
            GetDataSetList();
        }
        private void Window_Closing(object sender, System.ComponentModel.CancelEventArgs e)
        {
            Event.NCL.NCLEventBus.Unregister(this);
        }

        private void GetDataSetList()
        {
            if (RetDataSource != null)
            {
                Event.NCL.NCLEventBus.Publish(new Event.NCL.BeginGetDataSetListEvent(UIContext.Current.Token, RetDataSource.Id));
                _ctlHintMessage.Visibility = Visibility.Visible;
                _ctlDataSetList.Visibility = Visibility.Collapsed;
                _ctlSPbtns.IsEnabled = false;
            }
        }

        [Subscribe]
        public void EndGetDataSetList(Event.NCL.EndGetDataSetListEvent @event)
        {
            _dataSetList = new ObservableCollection<ServiceProxy.DesignServiceRef.DataSet>();
            Dispatcher.Invoke(() =>
            {
                _ctlHintMessage.Visibility = Visibility.Collapsed;
                _ctlDataSetList.Visibility = Visibility.Visible;
                _ctlSPbtns.IsEnabled = true;
                if (@event.State == Event.NCL.NCLEventState.Failure)
                {
                    _ctlSPbtns.Visibility = Visibility.Visible;
                }
                else if (@event.State == Event.NCL.NCLEventState.Finished)
                {
                    if (@event.DataSets != null && @event.DataSets.Length > 0)
                    {
                        foreach (var item in @event.DataSets)
                        {
                            _dataSetList.Add(item);
                        }
                    }
                }
                _ctlDataSetList.ItemsSource = _dataSetList;
            });
        }

        private void _ctlRetry_Click(object sender, RoutedEventArgs e)
        {
            GetDataSetList();
        }

    }
}
